//
//  PersonEditViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/25.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

enum PersonEditType {
    case email
    case phone
    case password
}

class PersonEditViewController: UIViewController {

    var editType: PersonEditType?
    
    var userProfileVM: UserProfileViewModel?
    
    let userAuthVM = UserAuthViewModel.shared
    
    var completion: (() -> Void)?
    
    let disposeBag = DisposeBag()
    
    let editField: UITextField = {
        let textfield = UITextField()
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .default
        return textfield
    }()
    
    let editFieldForNewPassword: UITextField = {
        let textfield = UITextField()
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .default
        textfield.isSecureTextEntry = true
        return textfield
    }()
    
    let editFieldForConfirmPassword: UITextField = {
        let textfield = UITextField()
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .default
        textfield.isSecureTextEntry = true
        return textfield
    }()
    
    let verifyCodeLength: Int = 6
    
    var toWaitSec: Int = 0
    
    var timer: Timer = Timer()
    let verifyTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "VERIFY_CODE")
        textField.font = AppFont(size: 14)
        textField.tintColor = UIColor.black
        textField.textColor = UIColor.gray
        textField.keyboardType = .numberPad
        return textField
    }()
    
    let getVerifyButton: UIButton = {
        let button = UIButton()
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.backgroundColor = lightSaperatorColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.setTitle(LanguageHelper.getString(key: "GET_VERIFY_CODE"), for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        button.titleLabel?.font = AppFont(size: 13)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        setBackBarItem()
        
        let rightBt = UIButton()
        rightBt.contentHorizontalAlignment = .right
        rightBt.setTitle(LanguageHelper.getString(key: "SUBMIT"), for: .normal)
        rightBt.setTitleColor(doneItemButtonColor, for: .normal)
        rightBt.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
        rightBt.sizeToFit()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
        
        if let type = editType {
            switch type {
            case .email:
                setViewEmail()
            case .password:
                setViewPasswd()
            case .phone:
                setViewPhone()
            }
        }
        
        initVM()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func submit(_ sender: UIBarButtonItem) {
        if let type = editType {
            switch type {
            case .email:
                verifyEmail()
            case .password:
                changePassword()
            case .phone:
                changePhone()
            }
        }
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                userProfileVM = UserProfileViewModel(token: token)
            }
        }
    }
    
    func setViewEmail() {
        self.navigationItem.title = LanguageHelper.getString(key: "CHANGE_EMAIL")
        self.editField.placeholder = LanguageHelper.getString(key: "WRITE_NEW_EMAIL")
        let emailView = UIView()
        emailView.backgroundColor = UIColor.white
        emailView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "NEW_EMAIL")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(emailView.bounds, UIEdgeInsetsMake(10, 10, 10, emailView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(emailView.bounds, UIEdgeInsetsMake(10, emailView.bounds.width - 200 - 10, 10, 10))
        let emailSaperator = UIView()
        emailSaperator.backgroundColor = lightSaperatorColor
        emailSaperator.frame = UIEdgeInsetsInsetRect(emailView.bounds, UIEdgeInsetsMake(emailView.bounds.height - 0.5, 0, 0, 0))
        
        let verifyView = UIView()
        verifyView.backgroundColor = UIColor.white
        verifyView.frame = CGRect(x: 0, y: menuHeight, width: self.view.bounds.width, height: menuHeight)
        let vtitleLabel = UILabel()
        vtitleLabel.font = AppFont(size: 14)
        vtitleLabel.textColor = UIColor.black
        vtitleLabel.text = LanguageHelper.getString(key: "VERIFYCODE")
        let vWidth = TextSize.textSize(text: vtitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        vtitleLabel.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, 10, 10, verifyView.bounds.width - vWidth - 10))
        verifyTextField.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, verifyView.bounds.width - 200 - 10, 10, 100))
        getVerifyButton.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, verifyView.bounds.width - 100 - 10, 10, 10))
        let vSaperator = UIView()
        vSaperator.backgroundColor = lightSaperatorColor
        vSaperator.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(verifyView.bounds.height - 0.5, 0, 0, 0))
        getVerifyButton.addTarget(self, action: #selector(getVerifyCode(_:)), for: .touchUpInside)
        
        emailView.addSubview(editField)
        emailView.addSubview(titleLabel)
        emailView.addSubview(emailSaperator)
        
        verifyView.addSubview(vtitleLabel)
        verifyView.addSubview(verifyTextField)
        verifyView.addSubview(getVerifyButton)
        verifyView.addSubview(vSaperator)
        self.view.addSubview(emailView)
        self.view.addSubview(verifyView)
    }

    func setViewPhone() {
        self.navigationItem.title = LanguageHelper.getString(key: "CHANGE_NUMBER")
        self.editField.placeholder = LanguageHelper.getString(key: "WRITE_NEW_NUMBER")
        let phoneView = UIView()
        phoneView.backgroundColor = UIColor.white
        phoneView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "NEW_NUMBER")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(phoneView.bounds, UIEdgeInsetsMake(10, 10, 10, phoneView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(phoneView.bounds, UIEdgeInsetsMake(10, phoneView.bounds.width - 100 - 10, 10, 10))
        let phoneSaperator = UIView()
        phoneSaperator.backgroundColor = lightSaperatorColor
        phoneSaperator.frame = UIEdgeInsetsInsetRect(phoneView.bounds, UIEdgeInsetsMake(phoneView.bounds.height - 0.5, 0, 0, 0))
        phoneView.addSubview(editField)
        phoneView.addSubview(titleLabel)
        phoneView.addSubview(phoneSaperator)
        self.view.addSubview(phoneView)
    }
    
    func setViewPasswd() {
        self.navigationItem.title = LanguageHelper.getString(key: "CHANGE_PW")
        self.editField.placeholder = LanguageHelper.getString(key: "WRITE_ORIGIN_PW")
        self.editField.isSecureTextEntry = true
        self.editFieldForNewPassword.placeholder = LanguageHelper.getString(key: "TYPE_NEW_PASSWORD")
        self.editFieldForConfirmPassword.placeholder = LanguageHelper.getString(key: "CONFIRM_NEW_PASSWORD")
        let passwdView = UIView()
        passwdView.backgroundColor = UIColor.white
        passwdView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight * 3)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "ORIGIN_PW")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(10, 10, menuHeight * 2 + 10, passwdView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(10, passwdView.bounds.width - 100 - 10, menuHeight * 2 + 10, 10))
        let passwdSaperator = UIView()
        passwdSaperator.backgroundColor = lightSaperatorColor
        passwdSaperator.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(passwdView.bounds.height - menuHeight * 2 - 0.5, 0, menuHeight * 2, 0))
    
        let newTitleLabel = UILabel()
        newTitleLabel.font = AppFont(size: 14)
        newTitleLabel.textColor = UIColor.black
        newTitleLabel.text = LanguageHelper.getString(key: "NEW_PASSWORD")
        let newTitleWidth = TextSize.textSize(text: newTitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        newTitleLabel.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(menuHeight + 10, 10, menuHeight + 10, passwdView.bounds.width - newTitleWidth - 10))
        editFieldForNewPassword.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(menuHeight + 10, passwdView.bounds.width - 100 - 10, menuHeight + 10, 10))
        let newPasswdSaperator = UIView()
        newPasswdSaperator.backgroundColor = lightSaperatorColor
        newPasswdSaperator.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(passwdView.bounds.height - menuHeight - 0.5, 0, menuHeight, 0))
        
        let conTitleLabel = UILabel()
        conTitleLabel.font = AppFont(size: 14)
        conTitleLabel.textColor = UIColor.black
        conTitleLabel.text = LanguageHelper.getString(key: "CONFIRM_NEW_PW")
        let conTitleWidth = TextSize.textSize(text: conTitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        conTitleLabel.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(menuHeight * 2 + 10, 10, 10, passwdView.bounds.width - conTitleWidth - 10))
        editFieldForConfirmPassword.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(menuHeight * 2 + 10, passwdView.bounds.width - 100 - 10, 10, 10))
        let conPasswdSaperator = UIView()
        conPasswdSaperator.backgroundColor = lightSaperatorColor
        conPasswdSaperator.frame = UIEdgeInsetsInsetRect(passwdView.bounds, UIEdgeInsetsMake(passwdView.bounds.height - 0.5, 0, 0, 0))
        
        passwdView.addSubview(editField)
        passwdView.addSubview(titleLabel)
        passwdView.addSubview(passwdSaperator)
        passwdView.addSubview(editFieldForNewPassword)
        passwdView.addSubview(newTitleLabel)
        passwdView.addSubview(newPasswdSaperator)
        passwdView.addSubview(editFieldForConfirmPassword)
        passwdView.addSubview(conTitleLabel)
        passwdView.addSubview(conPasswdSaperator)
        self.view.addSubview(passwdView)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if !editField.frame.contains(point) {
                editField.resignFirstResponder()
            }
            if !editFieldForNewPassword.frame.contains(point) {
                editFieldForNewPassword.resignFirstResponder()
            }
            if !editFieldForConfirmPassword.frame.contains(point) {
                editFieldForConfirmPassword.resignFirstResponder()
            }
            if !verifyTextField.frame.contains(point) {
                verifyTextField.resignFirstResponder()
            }
        }
    }
    
    func verifyEmail() {
        if let email = editField.text, let totp = verifyTextField.text {
            userAuthVM.verifyTOTP(email: email, totp: totp).subscribe(onNext: { [unowned self] result in
                if let con = result.totpValid {
                    if con {
                        self.changeEmail(result.token!)
                    } else {
                        self.showPromptView(message: LanguageHelper.getString(key: "EMAIL_VERIFY_FAIL"), confirmText: LanguageHelper.getString(key: "OK"))
                    }
                }
            })
            .addDisposableTo(disposeBag)
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "EMAIL_VERIFY_FAIL"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func changeEmail(_ token: String) {
        if let vm = userProfileVM {
            vm.changeEmail(token: token).subscribe(onNext: { [unowned self] response in
                if let status = response.status {
                    if status != 200 {
                        self.showPromptView(message: "\(LanguageHelper.getString(key: "ERROR_OCCUR")) \(status)", confirmText: LanguageHelper.getString(key: "OK"))
                    }
                } else {
                    if let success = response.success {
                        if success {
                            if let function = self.completion {
                                function()
                            }
                        } else {
                            if let data = response.data {
                                self.showPromptView(message: data, confirmText: LanguageHelper.getString(key: "OK"))
                            } else {
                                self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                            }
                        }
                    }
                }
            })
            .addDisposableTo(disposeBag)
        }
    }
    
    func changePhone() {
        if let vm = userProfileVM {
            if let phone = editField.text {
                vm.changePhone(phone: phone).subscribe(onNext: { [unowned self] response in
                    if let status = response.status {
                        if status != 200 {
                            self.showPromptView(message: "\(LanguageHelper.getString(key: "ERROR_OCCUR")) \(status)", confirmText: LanguageHelper.getString(key: "OK"))
                        }
                    } else {
                        if let success = response.success {
                            if success {
                                if let function = self.completion {
                                    function()
                                }
                            } else {
                                if let data = response.data {
                                    self.showPromptView(message: data, confirmText: LanguageHelper.getString(key: "OK"))
                                } else {
                                    self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                                }
                            }
                        }
                    }
                    })
                    .addDisposableTo(disposeBag)
            }
        }
    }
    
    func changePassword() {
        if let vm = userProfileVM {
            if let pwd = editField.text, let newPwd = editFieldForNewPassword.text, let conPwd = editFieldForConfirmPassword.text {
                if conPwd == newPwd {
                    if newPwd.count >= 4 {
                        vm.changePassword(password: pwd, newPassword: newPwd).subscribe(onNext: { [unowned self] response in
                            if let status = response.status {
                                if status != 200 {
                                    self.showPromptView(message: "\(LanguageHelper.getString(key: "ERROR_OCCUR")) \(status)", confirmText: LanguageHelper.getString(key: "OK"))
                                }
                            } else {
                                if let success = response.success {
                                    if success {
                                        JMSGUser.updateMyPassword(withNewPassword: newPwd.md5(), oldPassword: pwd.md5(), completionHandler: { [unowned self] (any, error) in
                                            if let function = self.completion {
                                                function()
                                            }
                                        })
                                    } else {
                                        if let data = response.data {
                                            self.showPromptView(message: data, confirmText: LanguageHelper.getString(key: "OK"))
                                        } else {
                                            self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                                        }
                                    }
                                }
                            }
                        })
                        .addDisposableTo(disposeBag)
                    } else {
                        self.showPromptView(message: LanguageHelper.getString(key: "AT_LEAST4"), confirmText: LanguageHelper.getString(key: "OK"))
                    }
                } else {
                    self.showPromptView(message: LanguageHelper.getString(key: "PASSWORD_DIFF"), confirmText: LanguageHelper.getString(key: "OK"))
                }
            }
        }
    }
    
    func getVerifyCode(_ sender: UIButton) {
        if Validate.email(editField.text!).isRight {
            //请求验证码
            userAuthVM.applyForRegisterEmail(email: editField.text!).subscribe(onNext: { json in
                if json is Bool {
                    if !(json as! (Bool)) {
                        self.showPromptView(message: LanguageHelper.getString(key: "EMAILADDR_REGISTERED"), confirmText: LanguageHelper.getString(key: "OK"))
                    }
                }
            }, onError: { error in
                print(error)
            })
            .addDisposableTo(disposeBag)
            //冷却按钮
            self.toWaitSec = 60
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
            self.getVerifyButton.isEnabled = false
            timer = Foundation.Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(waitToGetAgain), userInfo: nil, repeats: true)
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "INVALID_EMAIL"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func waitToGetAgain() {
        self.toWaitSec -= 1
        if self.toWaitSec == 0 {
            timer.invalidate()
            self.getVerifyButton.isEnabled = true
        } else {
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
